package com.ncf.jucai.accessmeter;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 * 入口 Created by lichengwen on 7/11/16.
 */
@Slf4j
public class Main
{

    public static void main(String[] args)
    {
        int port = 8081;
        if (args.length > 0) {
            if (args[0].matches("\\d+")) {
                port = Integer.parseInt(args[0]);
            } else {
                log.warn("argument[" + args[0] + "] is not number, using default port:" + port);
            }
        }

        try {
            AccessLogAnalyzer.go();
        } catch (Exception ex) {
            log.error("start AccessLogAnalyzer failed.", ex);
            System.exit(1);
        }

        try {
            startServer(port);
        } catch (Exception ex) {
            log.error("start http server failed.", ex);
            System.exit(1);
        }

    }

    private static void startServer(int port)
    {
        try {
            Server server = new Server(port);
            WebAppContext webAppContext = new WebAppContext(Main.class.getResource("/webroot").toString(), "/");
            webAppContext.setDescriptor(Main.class.getResource("/webroot/WEB-INF/web.xml").toString());
            webAppContext.setResourceBase(Main.class.getResource("/webroot").toString());
            webAppContext.setDisplayName("Jucai Access Meter");
            webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
            webAppContext.setConfigurationDiscovered(true);
            webAppContext.setParentLoaderPriority(true);

            HandlerList hList = new HandlerList();
            hList.addHandler(new MeterRenderer());
            hList.addHandler(webAppContext);

            server.setHandler(hList);
            server.start();
            server.join();
        } catch (Exception ex) {
            log.error("start access meter server failed.", ex);
        }
    }
}
